#FINAL DRAFT
#mark lihan
#esmee siy 
#troy espiritu
#cs161F



login=$(whoami)
loopcheck=1
menumode=0
touch ushop.$LOGNAME

date=$(date +"%d %b %Y")
fullname=$(cat /etc/passwd | grep -i ^$LOGNAME: | cut -d: -f5 | cut -d, -f1)

while [ "$loopcheck" = 1 ]
do

###################################################
########## MENU MODE CONTROLS #####################
###################################################
if test "$1" = '-m'; then
	if test "$#" = 1; then
		clear
		menumode=1
		loopcheck=1
		#echo "correct usage"
		echo "####### MENU MODE ####### "
		echo "(1)    Display shopping list"
		echo "(2)    Create new item"
		echo "(3)    Edit Existing item in list"
		echo "(4)    Mark item as Purchased"
		echo "(5)    Remove Item(s)"
		echo "(6)    Clear Purchased items list"
		echo "(7)    Clear entire list"
		echo "(8)    Help"
		echo "(9)    Quit"
		
		
			echo -n "enter choice: " 
			read mchoice
		
		
	else
		echo "Error in Menu Usage"
		exit
	fi
		
fi


###################################################
########## EDIT  CONTROLS #####################
###################################################
if test "$1" = '-e'|| test "$mchoice" = 3; then
	clear
	if test "$menumode" = 0; then
		
		if test $# -gt 2; then
		echo $#
		echo "wrong usage"
		exit
		fi
		
		loopcheck=0
		
	fi
	
	###########if using -e w/o arg or menu mode ##########
  if test "$#" = 1; then
	editcount=$(grep -c '|-' ushop.$LOGNAME)
	index3=1
	itemCount=0
	grep "|-" ushop.$LOGNAME > temp.$LOGNAME
	itemCount=$(grep -c '|' temp.$LOGNAME)
	awk -F "|" '{printf "%6d. %-30s %10.2f\n", NR, $1, $2}' temp.$LOGNAME
	rm temp.$LOGNAME
	
	if test $itemCount -gt 0; then
	
	echo -n "Indicate Item You Want to Edit?: "
	
	read editation
	
	if test $editation -le $itemCount && test $editation -ge 1; then
	
	
		olddesc=$(grep '|-' ushop.$LOGNAME|head -$editation|tail -1|cut -d'|' -f1)
		oldprice=$(grep '|-' ushop.$LOGNAME|head -$editation|tail -1|cut -d'|' -f2)
	
			
		newdesc=""
			
		while [ "$newdesc" = "" ]
		do
			echo -n "Enter New Item Description:$olddesc : "
			read newdesc
		done
	
		validprice=0
		
		until [ $validprice = 1 ]
		do
			echo -n "Enter Amount: "
			read newprice
			if echo $newprice | grep '\<[0-9]*\>' > /dev/null; then
			validprice=1
			fi
		done
	
		echo "$olddesc $oldprice to $newdesc $newprice"
		echo -n "Proceed with Update (y/n)?: "
		read confirmupdate
		if test "$confirmupdate" = "y"||test "$confirmupdate" = "Y"; then
			sed s/"$olddesc"/"$newdesc"/ ushop.$LOGNAME > buffer.$login
			sed s/"$oldprice"/"$newprice"/ buffer.$LOGNAME > buffer2.$login
		
			cp buffer2.$LOGNAME ushop.$LOGNAME
			rm buffer.$LOGNAME
			rm buffer2.$LOGNAME
			echo "Item updated"
			
			read ans
		
		else
			if test "$menumode" = 0; then
				echo "UPDATE UNSUCCESSFUL"
				exit
			else
				echo "UPDATE UNSUCCESSFUL"
				echo "ENTER to RETURN to MAIN"
				read ans
			fi
		fi	
	else
		if test "$menumode" = 0; then
			clear
			echo "No Item to Edit"
			exit
		else
			clear
			echo "No Item to Edit, ENTER to return to MAIN"
			read ans
		fi
	fi
	
	else
		clear
		echo "No Item to Edit, ENTER to return to MAIN"
		read ans
	
	fi
	
  else
	 
	 ############## if using search mode##############
	 
	 echo "$2 " > temp.$LOGNAME
    
    	 wordcount=$(wc -w temp.$LOGNAME | cut -d' ' -f1)
    	 tempcount=1
         rm temp.$LOGNAME
    
    	touch temp.$LOGNAME
    	grep '|-' ushop.$LOGNAME > item.$LOGNAME
    
    	while [ $wordcount -ge $tempcount ]; do
      	grep -i $(echo $2 | cut -d' ' -f$tempcount) item.$LOGNAME >> temp.$LOGNAME
      	tempcount=`expr $tempcount + 1`
    	done
	
	
    	#                        #remove duplications in temp.$LOGNAME
	itemcount=$(grep -c '|' temp.$LOGNAME)
    	awk -F "|" '{printf "%6d. %-30s %10.2f\n", NR, $1, $2}' temp.$LOGNAME
	
	## almost the code above. actually the same code... redundant##	
	
	
	if test $itemcount -gt 0; then
	
	echo -n "Indicate Item You Want to Edit?: "
	
	read editation
	
	if test $editation -le $itemcount && test $editation -ge 1; then
	
	
		olddesc=$(grep '|-' temp.$LOGNAME|head -$editation|tail -1|cut -d'|' -f1)
		oldprice=$(grep '|-' temp.$LOGNAME|head -$editation|tail -1|cut -d'|' -f2)
	
		newdesc=""
			
		while [ "$newdesc" = "" ]
		do
			echo -n "Enter New Item Description:$olddesc : "
			read newdesc
		done
	
		validprice=0
		
		until [ $validprice = 1 ]
		do
			echo -n "Enter Amount: "		
			read newprice
			if echo $newprice | grep '\<[0-9]*\>' > /dev/null; then
			validprice=1
			fi
		done
	
		echo "$olddesc $oldprice to $newdesc $newprice"
		echo -n "Proceed with Update (y/n)?: "
		read confirmupdate
		if test "$confirmupdate" = "y"||test "$confirmupdate" = "Y"; then
			sed s/"$olddesc"/"$newdesc"/ ushop.$LOGNAME > buffer.$login
			sed s/"$oldprice"/"$newprice"/ buffer.$LOGNAME > buffer2.$login
		
			cp buffer2.$LOGNAME ushop.$LOGNAME
			rm buffer.$LOGNAME
			rm buffer2.$LOGNAME
			echo "Item updated"
			
			read ans
		
		else
			if test "$menumode" = 0; then
				echo "UPDATE UNSUCCESSFUL"
				exit
			else
				echo "UPDATE UNSUCCESSFUL"
				echo "ENTER to RETURN to MAIN"
				read ans
			fi
		fi	
	else
		#if test "$menumode" = 0; then
			clear
			echo "No Item to Edit"
			exit
		
		#fi
	fi
	
	else
	
		if test "$menumode" = 0; then
			clear
			echo "No Item to Edit"
			exit
		else
			clear
			echo "No Item to Edit, ENTER to return to MAIN"
			read ans
		fi
	fi
    
  fi
	
	
###################################################
########## DISPLAY CONTROLS #####################
###################################################

elif test $# -eq 0 || test "$1" = '-d' || test "$mchoice" = 1; then
	clear
  	if test "$menumode" = 0; then
		loopcheck=0
	fi
  
 echo "$fullname's Shopping List as of today, $date"
  echo "-----------------------------------------------------"
  echo ""
  itemcount=$(grep -c -i "|-" ushop.$LOGNAME) 
  purcount=$(grep -c -i -v "|-" ushop.$LOGNAME) 
  if test $(grep -c '|' ushop.$LOGNAME) -eq 0; then
    echo "No items on the list."
  else
    echo "Remaining items"
    itemsum=0
    pursum=0
    grep '|-' ushop.$LOGNAME > item.$LOGNAME
    awk -F "|" ' BEGIN {total=0 }
    { printf "  %6d. %-30s %14.2f\n", NR, $1, $2
      total+=$2 } 
    END { printf "                                          --------------\n" 
          printf "Total remaining items %33.2f\n", total} ' item.$LOGNAME
    rm item.$LOGNAME
    echo ""
    echo "Purchased items"
    grep -v '|-' ushop.$LOGNAME > pur.$LOGNAME
    awk -F "|" ' BEGIN {total=0 }
    { printf "  %6d. %-30s %14.2f (%11s)\n", NR, $1, $2, $3
      total+=$2 }
    END { printf "                                          --------------\n" 
          printf "Total purchased items %33.2f\n", total} ' pur.$LOGNAME
    rm pur.$LOGNAME
    echo ""
    awk -F "|" ' BEGIN {total=0 } { total+=$2 }
    END { printf "GRAND TOTAL %43.2f\n", total} ' ushop.$LOGNAME
    
  fi
  
	if test "$menumode" = 0; then
		exit
	else
		echo "Enter to Return to MAIN"
		read ans
	fi
  
###################################################
########## CREATE NEW CONTROLS #####################
###################################################

elif test "$1" = '-i' || test "$mchoice" = 2; then

	clear
  	if test "$menumode" = 0; then
		loopcheck=0
	fi

	if test $menumode -eq 0 && test $# -gt 3; then
		clear
		echo "wrong usage"
		exit
	fi
	


  price=0
  productname=""
  echo ""
  if [ $# -eq 1 ] 
  then
  	while [ "$productname" = "" ]  
	do
    echo -n "Please input the product name. " 
    read productname
    	done
    echo ""
    echo -n "How much does the item cost? "
    read price
  elif [ $# -eq 2 ]
  then
    productname=$2
    echo -n "How much does the item cost? "
    read price
  elif [ $# -eq 3 ] 
  then
    productname=$2
    price=$3    
  fi
  if echo $price | grep '\<[0-9]*\>' > /dev/null; then
    echo ""
    echo "The item \"$productname\" priced at $price has been created."
    echo "$productname|$price|-" >> ushop.$LOGNAME
    echo "It has been added to your list of items to be purchased."
  else
    echo ""
    echo "Invalid number format."
  fi
  
	if test "$menumode" = 0; then
		exit
	else
		echo "Enter to Return to MAIN"
		read ans
	fi
  
###################################################
########## PURCHASE CONTROLS #####################
###################################################

elif test "$1" = '-p' || test "$mchoice" = 4; then

  
  clear
  touch temp.$LOGNAME
  if [ $# -eq 2 ]; then
    echo "$2 " > temp.$LOGNAME
    wordcount=$(wc -w temp.$LOGNAME | cut -d' ' -f1)
    tempcount=1
    rm temp.$LOGNAME
    touch temp.$LOGNAME
    grep '|-' ushop.$LOGNAME > item.$LOGNAME
    while [ $wordcount -ge $tempcount ]; do
      grep -i $(echo $2 | cut -d' ' -f$tempcount) item.$LOGNAME >> temp.$LOGNAME
      tempcount=`expr $tempcount + 1`
    done
    #                        #remove duplications in temp.$LOGNAME
    itemcount=$(grep -c '|' temp.$LOGNAME)
    awk -F "|" '{printf "%6d. %-30s %14.2f\n", NR, $1, $2 }' temp.$LOGNAME
  elif [ $# -eq 1 ]; then
    grep '|-' ushop.$LOGNAME > temp.$LOGNAME
    itemcount=$(grep -c '|' temp.$LOGNAME)
    awk -F "|" '{printf "%6d. %-30s %14.2f\n", NR, $1, $2 }' temp.$LOGNAME
  fi
  if [ $(wc -l temp.$LOGNAME | cut -d' ' -f1) -gt 0 ]; then
    echo ""
    echo -n "Indicate item number do you want to purchase (Enter purchases everything): " 
    read ans
      if [ "$ans" = "" ]; then
        echo ""; echo -n "Purchase all items above (y/n)? "
	read yorn
	if [ "$yorn" = "y" ]; then
       	  tempcount=1
          while [ $(wc -w temp.$LOGNAME | cut -d' ' -f1) -ge $tempcount ]; do
             item=$(cat temp.$LOGNAME | head -$tempcount | tail -1 | cut -d'|' -f1)
             price=$(cat temp.$LOGNAME | head -$tempcount | tail -1 | cut -d'|' -f2)
             cat ushop.$LOGNAME | sed s/"$item|$price|-"/"$item|$price|$date"/ > temp2.$LOGNAME
             cp temp2.$LOGNAME ushop.$LOGNAME
             tempcount=`expr $tempcount + 1`
          done
          echo ""; echo "All items listed above have been purchased."
	else
	  echo ""; echo "No item was purchased"
	fi
      elif test $ans -ge 1 && test $ans -le $itemcount; then
      price=$(cat temp.$LOGNAME | head -$ans | tail -1 | cut -d'|' -f2)
        product=$(cat temp.$LOGNAME | cut -d'|' -f1 | head -$ans | tail -1)
        echo ""; echo -n "Purchase the item \"$product\" (y/n)? "
        read yorn
        if [ "$yorn" = "y" ]; then
          grep -v "$product|$price" ushop.$LOGNAME > pur.$LOGNAME
          grep -i "$product|$price" ushop.$LOGNAME | sed s/-/"$date"/ >> pur.$LOGNAME
          cp pur.$LOGNAME ushop.$LOGNAME
          rm pur.$LOGNAME
          echo ""; echo "Item purchased."
        else
          echo ""; echo "Item was not purchased."
        fi
      else
        echo ""; echo "The number doesn't point to any item or invalid number format."
      fi 
  else
    echo "Did not find any matching item in the to-buy list."
  fi
  rm temp.$LOGNAME
  
  	if test "$menumode" = 0; then
		exit
	else
		echo "Enter to Return to MAIN"
		read ans
	fi




###################################################
########## REMOVE ITEMS CONTROLS ###############
###################################################
elif test "$1" = '-r' || test $mchoice = 5; then

	clear
  	if test "$menumode" = 0; then
		loopcheck=0
	fi

  if [ "$#" -gt 2 ]; then
    echo "     Incorrect input format. Multiple item search should be enclosed in ' '"
    exit
  else
    #creates new tempfiles
    touch temp.$LOGNAME.rem
    touch remtemp.$LOGNAME.rem
    #searches for all remaining items and places it in remtemp
    grep -i "|-" ushop.$LOGNAME > remtemp.$LOGNAME.rem
    #user presses enter 
    if [ "$2" = "" ]; then
      
       awk -F "|" '{printf"%6d. %-30s %14.2f\n" ,NR, $1, $2 }' remtemp.$LOGNAME.rem
       if [ $(cat remtemp.$LOGNAME.rem  | wc -l  | cut -d' ' -f1) -eq 0 ]; then 
          echo "     There are no items to remaining items to delete"
          exit
       else
	   echo ""
          echo -n "     Indicate item number you want to delete (enter deletes everything): "
          read in
          ulimit=0
          ulimit=$( wc -l remtemp.$LOGNAME.rem | cut -d' ' -f1 )
          if  echo $in | grep '\<[0-9]*\>' > /dev/null; then
              if [ $in -le $ulimit ]; then
              item=$(cat remtemp.$LOGNAME.rem | head -$in | tail -1 | cut -d'|' -f1 )
              origitem=$(grep "$item" ushop.$LOGNAME | cut -d'|' -f1 )
              origitemnum=0
              origitemnum=$(grep -n "$origitem" ushop.$LOGNAME | cut -d'|' -f1 | cut -d':' -f1)
              echo -n "     Delete the item \"$origitem\" (y/n)? "
              read yn                 
                 if [ "$yn" = "y" ]; then
                    sed "${in}d" remtemp.$LOGNAME.rem | cat > remtemp.$LOGNAME.rem
                    sed "${origitemnum}d" ushop.$LOGNAME | cat > ushop.$LOGNAME
                    echo '     Item deleted.'
                 else
                    
		    
		     if test "$menumode" = 0; then
		     exit
		     else
		     echo "Enter to Return to MAIN"
		     read ans
		     fi
                 
		 
		 
		 fi
              else
		    echo "     Invalid input."
                     
		     if test "$menumode" = 0; then
		     exit
		     else
		     echo "Enter to Return to MAIN"
		     read ans
		     fi
              fi           
              elif [ "$in" = "" ]; then    
                echo -n "     Delete all items above (y/n)? "
	         read yn
	         if [ "$yn" = "y" ]; then
                    grep -v '|-' ushop.$LOGNAME | cat > ushop.$LOGNAME
                    echo "     All items in your to-buy list have been deleted."
       	  else
	             
		     if test "$menumode" = 0; then
		     exit
		     else
		     echo "Enter to Return to MAIN"
		     read ans
		     fi
		     	
                fi		
            else
                     if test "$menumode" = 0; then
		     exit
		     else
		     echo "Enter to Return to MAIN"
		     read ans
		     fi
            fi     
          fi  
     #searches matching items for multiple queries
     else
        echo $2 > wc.$LOGNAME.rem
        wordnum=0
        wordnum=$(wc -w wc.$LOGNAME.rem | cut -d' ' -f1)
        while [ $wordnum -gt 0 ]; do
           item=$( echo $2 | cut -d' ' -f$wordnum )
           grep -i "$item" remtemp.$LOGNAME.rem >> temp.$LOGNAME.rem
           wordnum=`expr $wordnum - 1`
        done
        #displays matching items
        echo ""
        awk -F "|" '{printf"%6d. %-30s %14.2f\n" ,NR, $1, $2 }' temp.$LOGNAME.rem
    
        if [ $(cat temp.$LOGNAME.rem  | wc -l  | cut -d' ' -f1) -eq 0 ]; then 	          
           echo "     There are no remaining items that matches search"
           exit  	
        else 	
           echo ""
           echo -n "     Indicate item number you want to delete (enter deletes everything): "
           #user enters item number to be deleted
           read input
           ulimit=$( wc -l temp.$LOGNAME.rem | cut -d' ' -f1 )
           if  echo $input | grep '\<[0-9]*\>' > /dev/null; then
              if [ $input -le $ulimit ]; then
              item=$(cat temp.$LOGNAME.rem | head -$input | tail -1 | cut -d'|' -f1 )
              origitem=$(grep "$item" ushop.$LOGNAME | cut -d'|' -f1 )
              origitemnum=0
              origitemnum=$(grep -n "$origitem" ushop.$LOGNAME | cut -d'|' -f1 | cut -d':' -f1 )
              echo -n "     Delete the item \"$origitem\" (y/n)? "
              read yn
                 if [ "$yn" = "y" ]; then
                    sed "${input}d" temp.$LOGNAME.rem | cat > temp.$LOGNAME.rem
                    sed "${origitemnum}d" ushop.$LOGNAME | cat > ushop.$LOGNAME
                    echo "     Item deleted."
                 else
                    
		     if test "$menumode" = 0; then
		     exit
		     else
		     echo "Enter to Return to MAIN"
		     read ans
		     fi
		    
                 fi
              else
		   echo "     Invalid input."
		   
		   if test "$menumode" = 0; then
		   exit
	           else
		   echo "Enter to Return to MAIN"
		   read ans
	           fi
		   	
              fi
            elif [ "$input" = "" ]; then
                itemcount=0
                itemcount=$( wc -l temp.$LOGNAME.rem | cut -d' ' -f1 )
                while [ $itemcount -gt 0 ]; do
                   item=$(cat temp.$LOGNAME.rem | tail -l )
                   tempnum=$(grep -n "$item" temp.$LOGNAME.rem | cut -d':' -f1)
                   tempnum=$(echo $tempnum | cut -d' ' -f1)
                   sed "${tempnum}d" temp.$LOGNAME.rem | cat > temp.$LOGNAME.rem
                   orignum=$(grep -n "$item" ushop.$LOGNAME | cut -d':' -f1 )
		     orignum=$(echo $orignum | cut -d' ' -f1)
                   sed "${orignum}d" ushop.$LOGNAME | cat > ushop.$LOGNAME
		     itemcount=`expr $itemcount - 1`
                done
                                    
           fi
       fi
     fi   
  fi
  
  rm temp.$LOGNAME.rem
  rm remtemp.$LOGNAME.rem
  
  
  
	if test "$menumode" = 0; then
		exit
	else
		echo "Enter to Return to MAIN"
		read ans
	fi	
	

	

###################################################
########## CLEAR PURCHASED CONTROLS ###############
###################################################

elif test "$1" = '-c' || test $mchoice = 6; then

	clear
  	if test "$menumode" = 0; then
		loopcheck=0
	fi
	
	
	
	
	if [ "$2" = "" ]; then
	
    	    if test $(grep -c -v '|-' ushop.$LOGNAME) != 0; then
		echo -n "Do you want to remove all PURCHASED items from the list (y/n)? "
    		read input
    		if [ "$input" = "y" ]; then
       			grep '|-' ushop.$LOGNAME | cat > ushop.$LOGNAME		
       			echo 'Your purchased items have been cleared from the shopping list.' 
       			#cat ushop.$LOGNAME	
    		else
        		echo "Not Cleared"
    		fi
	    else
	    	echo "PURCHASED LIST IS EMPTY"
	    fi
		
		
	else
		echo "Error in Usage"	
  	fi
		
		
		
		
		
	if test "$menumode" = 0; then
		exit
	else
		echo "Enter to Return to MAIN"
		read ans
	fi
###################################################
########## CLEAR ALL CONTROLS #####################
###################################################


elif test "$1" = '-C' || test $mchoice = 7; then
	clear
  	if test "$menumode" = 0; then
		loopcheck=0
		
		if test $# -gt 1; then
		echo "Wrong Usage"
		else
		
			if test $(grep -c '|' ushop.$LOGNAME) -eq 0; then
    				echo "No items on the list."
			else
		
				echo -n "Do You Want to Remove All Items from the List?(y/n): "
				read remAllAns
		
				if test "$remAllAns" = "y" || test "$remAllAns" = "Y"; then
					rm ushop.$LOGNAME
					touch ushop.$LOGNAME
					echo "ALL Items Have Been Removed"
				fi
			fi
		fi
	else
		if test $(grep -c '|' ushop.$LOGNAME) -eq 0; then
    				echo "No items on the list."
		else
			echo -n "Do You Want to Remove All Items from the List?(y/n): "
			read remAllAns
		
			if test "$remAllAns" = "y" || test "$remAllAns" = "Y"; then
				rm ushop.$LOGNAME
				touch ushop.$LOGNAME
				echo "ALL Items Have Been Removed"
			fi
		fi	
	
  	fi
	
	if test "$menumode" = 0; then
		exit
	else
		echo "Enter to Return to MAIN"
		read ans
	fi
  

###################################################
########## HELP CONTROLS #####################
###################################################
	
elif test "$1" = '-h'||test "$mchoice" = 8; then
	
	if test "$menumode" = 0; then
		
		if test "$#" = 1; then
			loopcheck=0
		else
			echo "Error in Usage"
			exit
		fi
		
		clear
		echo "####### HELP SCREEN #######"
		echo "-i (create item, 0-2 arguments) "
		echo "-e (edit item, 0-1 arguments) "
		echo "-p (mark item as purchased, 0-1 arguments) "
		echo "-r (remove items or items from list, 0-1 arguments) "
		echo "-d (display list, 0 arguments) "
		echo "-C (clear entire list, 0 arguments) "
		echo "-c (clear purchased items only, 0 arguments) "
		echo "-m (menu mode, 0 arguments) "
		echo "-h (help screen, 0 arguments) "
	
	else
		clear
		echo "####### HELP SCREEN #######"
		echo "-i (create item, 0-2 arguments) "
		echo "-e (edit item, 0-1 arguments) "
		echo "-p (mark item as purchased, 0-1 arguments) "
		echo "-r (remove items or items from list, 0-1 arguments) "
		echo "-d (display list, 0 arguments) "
		echo "-C (clear entire list, 0 arguments) "
		echo "-c (clear purchased items only, 0 arguments) "
		echo "-m (menu mode, 0 arguments) "
		echo "-h (help screen, 0 arguments) "
		echo " "
		echo -n "Return to menu"
		read ans
	fi

		
		
fi

###################################################
########## QUIT CONTROLS #####################
###################################################

if test "$mchoice" = 9; then
	loopcheck=0
	clear
fi

done
